from rest_framework import serializers
from rest_framework.generics import ListCreateAPIView
from rest_framework.filters import BaseFilterBackend
from api.utils.auth import UserAuthentication
from api.utils.auth import GeneralAuthorization
from api import models

class CommentBaseFilterBackend(BaseFilterBackend):

    def filter_queryset(self, request, queryset, view):
        news_id=request.query_params.get('news_id')
        if news_id:
            return queryset.filter(news_id=news_id)
        else:
            return queryset

class CommentListSerializer(serializers.ModelSerializer):
    class Meta:
        model=models.CommentRecord
        fields='__all__'

class CommentCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model=models.CommentRecord
        exclude =['user','create_date','favor_count']

class CommentApiView(ListCreateAPIView):
    queryset = models.CommentRecord.objects
    filter_backends = [CommentBaseFilterBackend,]

    def get_serializer_class(self):
        if self.request.method == 'POST':
            return CommentCreateSerializer
        if self.request.method == 'GET':
            return CommentListSerializer

    def perform_create(self, serializer):
        serializer.save(user_id=1)

    def get_authenticators(self):
        if self.request.method == 'POST':
            return [UserAuthentication(),]
        if self.request.method == 'GET':
            return [GeneralAuthorization(),]